<template>
  <Dialog
    :model-value="dialogVisible"
    :title="dialogProps.title"
    :fullscreen="dialogProps.fullscreen"
    :max-height="dialogProps.maxHeight"
    :cancel-dialog="cancelDialog"
    width="80%"
    top="7vh"
  >
    <div :style="'width: calc(100% - ' + dialogProps.labelWidth! / 2 + 'px)'">
      <el-form
        ref="ruleFormRef"
        label-position="right"
        :label-width="dialogProps.labelWidth + 'px'"
        :rules="rules"
        :model="dialogProps.row"
        :disabled="dialogProps.isView"
        :hide-required-asterisk="dialogProps.isView"
      >
        <!-- 合同编号 -->
        <el-form-item label="合同编号" prop="number" v-if="dialogProps.row!.id">
          <el-input v-model="dialogProps.row!.number" readonly show-word-limit></el-input>
        </el-form-item>
        <!-- 合同名称 -->
        <el-form-item label="合同名称" prop="name">
          <el-input v-model="dialogProps.row!.name" clearable maxlength="100" show-word-limit placeholder="请输入合同名称"></el-input>
        </el-form-item>
        <!-- 签约客户 -->
        <el-form-item label="签约客户" prop="customerId">
          <div class="flex" style="width: 100%">
            <el-input v-model="dialogProps.row!.customerName" placeholder="请选择要签约的客户" class="mr-18px" disabled> </el-input>
            <el-button type="primary" @click="openCustomerDialog">选择客户</el-button>
            <CustomerDialog ref="customerRef" @get-customer-data="handleCustomerSelect" />
          </div>
        </el-form-item>
        <!-- 时间选择区 -->
        <div class="flex" style="width: 100%">
          <el-form-item label="合同开始时间" prop="startTime">
            <el-date-picker
              v-model="dialogProps.row!.startTime"
              type="date"
              placeholder="选择合同开始时间"
              value-format="YYYY-MM-DD"
              :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="合同结束时间" prop="endTime">
            <el-date-picker
              v-model="dialogProps.row!.endTime"
              type="date"
              placeholder="选择合同结束时间"
              value-format="YYYY-MM-DD"
              :disabled-date="disableEndDate"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="合同签约时间" prop="signTime">
            <el-date-picker
              v-model="dialogProps.row!.signTime"
              type="date"
              placeholder="选择合同签约时间"
              value-format="YYYY-MM-DD"
              :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
              style="width: 100%"
            />
          </el-form-item>
        </div>
        <!-- 金额区 -->
        <div class="flex" style="width: 100%">
          <el-form-item label="合同总金额" prop="amount" style="flex: 1">
            <el-input v-model="dialogProps.row!.amount" readonly placeholder="自动计算"></el-input>
          </el-form-item>
          <el-form-item label="已收款项" prop="receivedAmount" style="flex: 1">
            <el-input v-model="dialogProps.row!.receivedAmount" clearable placeholder="请输入已收款项" type="number">
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>
        </div>
        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dialogProps.row!.remark" clearable type="textarea" maxlength="100" show-word-limit placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>

      <!-- 商品选择区域 -->
      <div style="width: 100%; margin-top: 20px">
        <h2>合同商品</h2>
        <el-divider />
        <el-alert
          v-if="dialogProps.row.products && dialogProps.row.products.length > 0"
          :title="`已选择 ${dialogProps.row.products.length} 个商品，合同总金额：¥${dialogProps.row.amount || '0.00'}`"
          type="info"
          :closable="false"
          style="margin-bottom: 15px"
        />

        <el-table :data="dialogProps.row.products" border style="width: 100%" v-loading="productLoading">
          <el-table-column prop="pName" label="商品名称" min-width="200">
            <template #default="scope">
              <div class="product-selector">
                <el-input v-model="scope.row.pName" placeholder="请选择商品" style="width: 180px" readonly :class="{ 'error-border': !scope.row.pId || scope.row.pId === 0 }" />
                <el-button type="primary" style="margin-left: 5px" @click="openProductDialog(scope.$index)">
                  {{ scope.row.pId && scope.row.pId !== 0 ? '更换商品' : '选择商品' }}
                </el-button>
                <div v-if="scope.row.stock !== undefined" class="stock-info"> 库存: {{ scope.row.stock }} | 销量: {{ scope.row.sales || 0 }} </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template #default="scope">
              <span v-if="scope.row.price">¥{{ scope.row.price.toFixed(2) }}</span>
              <span v-else class="text-gray">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="数量" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.count"
                :min="1"
                :max="getMaxCount(scope.row)"
                @change="handleCountChange(scope.row)"
                style="width: 100px"
                :disabled="!scope.row.pId || scope.row.pId === 0"
              />
              <!-- 修复库存显示逻辑 -->
              <div v-if="scope.row.stock !== undefined" class="stock-info">
                <span v-if="scope.row.count > scope.row.stock" class="stock-warning">库存不足！当前库存: {{ scope.row.stock }}</span>
                <span v-else>可用库存: {{ scope.row.stock - scope.row.count }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="小计" width="120">
            <template #default="scope">
              <span v-if="scope.row.totalPrice">¥{{ scope.row.totalPrice.toFixed(2) }}</span>
              <span v-else class="text-gray">-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" link @click="removeContractProduct(scope.$index)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="display: flex; justify-content: center; width: 100%; margin-top: 20px; gap: 16px">
          <el-button type="primary" @click="addContractProduct" :icon="Plus">添加商品</el-button>
          <el-button type="success" @click="openBatchProductDialog" :icon="ShoppingCart">批量选择商品</el-button>
        </div>

        <!-- 金额汇总 -->
        <div v-if="dialogProps.row.products && dialogProps.row.products.length > 0" class="amount-summary">
          <el-descriptions title="金额汇总" :column="2" border>
            <el-descriptions-item label="商品数量">{{ dialogProps.row.products.length }} 个</el-descriptions-item>
            <el-descriptions-item label="商品总金额">¥{{ dialogProps.row.amount || '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="已收款项">¥{{ dialogProps.row.receivedAmount || '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="待收款项">
              ¥{{ (parseFloat(dialogProps.row.amount || 0) - parseFloat(dialogProps.row.receivedAmount || 0)).toFixed(2) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </div>

    <!-- 商品选择对话框 -->
    <ProductDialog ref="productRef" @get-product-data="handleProductSelect" />

    <template #footer>
      <slot name="footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" v-show="!dialogProps.isView" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </slot>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import CustomerDialog from './CustomerDialog.vue'
import ProductDialog from './ProductDialog.vue'
import { Plus, ShoppingCart } from '@element-plus/icons-vue'

interface DialogProps {
  title: string
  isView: boolean
  fullscreen?: boolean
  row: any
  labelWidth?: number
  maxHeight?: number | string
  api?: (params: any) => Promise<any>
  getTableList?: () => Promise<any>
}

const dialogVisible = ref(false)
const dialogProps = ref<DialogProps>({
  isView: false,
  title: '',
  row: {
    products: [],
    amount: 0,
    receivedAmount: 0,
    status: 0
  },
  labelWidth: 120,
  fullscreen: false,
  maxHeight: '600px'
})

const submitLoading = ref(false)
const productLoading = ref(false)

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入合同名称', trigger: 'blur' },
    { min: 2, max: 100, message: '合同名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  customerId: [{ required: true, message: '请选择签约客户', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择合同开始时间', trigger: 'change' }],
  endTime: [
    { required: true, message: '请选择合同结束时间', trigger: 'change' },
    { validator: validateEndTime, trigger: 'change' }
  ],
  signTime: [{ required: true, message: '请选择合同签约时间', trigger: 'change' }],
  receivedAmount: [{ validator: validateReceivedAmount, trigger: 'blur' }]
})

// 验证结束时间
function validateEndTime(rule: any, value: any, callback: any) {
  if (!value) {
    callback(new Error('请选择合同结束时间'))
    return
  }
  if (dialogProps.value.row.startTime && value < dialogProps.value.row.startTime) {
    callback(new Error('合同结束时间不能早于开始时间'))
  } else {
    callback()
  }
}

// 验证已收金额
function validateReceivedAmount(rule: any, value: any, callback: any) {
  if (value && parseFloat(value) > parseFloat(dialogProps.value.row.amount || 0)) {
    callback(new Error('已收款项不能大于合同总金额'))
  } else {
    callback()
  }
}

// 禁用结束日期
const disableEndDate = (time: Date) => {
  if (!dialogProps.value.row.startTime) return false
  const startTime = new Date(dialogProps.value.row.startTime)
  return time.getTime() < startTime.getTime()
}

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps): void => {
  const defaultRow = {
    products: [],
    amount: 0,
    receivedAmount: 0,
    status: 0
  }

  if (params.row && !params.row.products) {
    params.row.products = []
  }

  params.row = { ...defaultRow, ...params.row }

  // 初始化商品数据，确保有库存信息
  if (params.row.products) {
    params.row.products = params.row.products.map((product: any) => ({
      ...product,
      count: product.count || 1,
      stock: product.stock || 0,
      sales: product.sales || 0,
      totalPrice: (product.price || 0) * (product.count || 1)
    }))
  }

  dialogProps.value = { ...dialogProps.value, ...params }
  dialogVisible.value = true

  // 计算总金额
  calculateTotalAmount()

  // 监听商品变化
  watch(() => dialogProps.value.row.products, calculateTotalAmount, { deep: true })
  console.log('=== 接收合同参数结束 ===')
}

defineExpose({
  acceptParams
})

const ruleFormRef = ref<FormInstance>()

const handleSubmit = async () => {
  if (!ruleFormRef.value) return

  try {
    await ruleFormRef.value.validate()
  } catch (error) {
    ElMessage.warning('请完善表单信息')
    return
  }

  // 验证每个商品是否选择了商品信息
  const invalidProducts = dialogProps.value.row.products.filter((product: any) => !product.pId || product.pId === 0)
  if (invalidProducts.length > 0) {
    ElMessage.warning('请为所有商品选择具体的商品信息')
    return
  }

  // 验证商品数量不超过库存
  const outOfStockProducts = dialogProps.value.row.products.filter((product: any) => product.count > getMaxCount(product))
  if (outOfStockProducts.length > 0) {
    ElMessage.warning('部分商品数量超过库存限制，请调整数量')
    return
  }

  // 确保状态有值
  if (dialogProps.value.row.status === undefined || dialogProps.value.row.status === null) {
    dialogProps.value.row.status = 0
  }

  // 转换数据类型
  const submitData = {
    ...dialogProps.value.row,
    amount: parseFloat(dialogProps.value.row.amount || 0),
    receivedAmount: parseFloat(dialogProps.value.row.receivedAmount || 0),
    customerId: parseInt(dialogProps.value.row.customerId),
    products: dialogProps.value.row.products
      .filter((product: any) => product.pId > 0)
      .map((product: any) => ({
        pId: parseInt(product.pId),
        pName: product.pName,
        price: parseFloat(product.price || 0),
        count: parseInt(product.count || 0),
        totalPrice: parseFloat(product.totalPrice || 0)
      }))
  }

  console.log('提交数据:', submitData)

  submitLoading.value = true
  try {
    // 清理不需要的字段
    delete submitData['updateTime']
    delete submitData['createTime']
    delete submitData['customerName']

    await dialogProps.value.api!(submitData)
    ElMessage.success({ message: `${dialogProps.value.title}成功！` })
    dialogProps.value.getTableList!()
    dialogVisible.value = false
    ruleFormRef.value!.resetFields()
    cancelDialog(true)
  } catch (error: any) {
    console.error('保存合同失败:', error)
    ElMessage.error(error.message || `${dialogProps.value.title}失败，请重试`)
  } finally {
    submitLoading.value = false
  }
}

const cancelDialog = (isClean?: boolean) => {
  dialogVisible.value = false
  let condition = ['查看', '编辑']
  if (condition.includes(dialogProps.value.title) || isClean) {
    dialogProps.value.row = { products: [], amount: 0, receivedAmount: 0, status: 0 }
    ruleFormRef.value!.resetFields()
  }
}

// 客户选择相关
const customerRef = ref()
const openCustomerDialog = () => {
  const params = {
    title: '客户列表',
    fullscreen: false,
    maxHeight: '500px'
  }
  customerRef.value.acceptParams(params)
}

const handleCustomerSelect = (val: any) => {
  if (val.id && val.name) {
    dialogProps.value.row.customerId = val.id
    dialogProps.value.row.customerName = val.name
  }
}

// 商品选择相关
const productRef = ref()
const currentProductIndex = ref(-1)

// 打开单个商品选择
const openProductDialog = (index: number) => {
  currentProductIndex.value = index
  const params = {
    title: '选择商品',
    fullscreen: false,
    maxHeight: '500px',
    selectionLimit: 1
  }
  productRef.value?.acceptParams(params)
}

// 打开批量商品选择
const openBatchProductDialog = () => {
  currentProductIndex.value = -1
  const params = {
    title: '批量选择商品',
    fullscreen: false,
    maxHeight: '500px',
    selectionLimit: 0
  }
  productRef.value?.acceptParams(params)
}

// 接收商品数据
const handleProductSelect = (productData: any) => {
  console.log('接收到商品数据:', productData)

  if (currentProductIndex.value === -1) {
    // 批量选择模式
    if (Array.isArray(productData)) {
      let addedCount = 0
      productData.forEach((product) => {
        if (addProductToContract(product)) addedCount++
      })
      ElMessage.success(`成功添加 ${addedCount} 个商品`)
    }
  } else {
    // 单个选择模式
    if (productData && productData.id) {
      const product = dialogProps.value.row.products[currentProductIndex.value]
      product.pId = productData.id
      product.pName = productData.name
      product.price = productData.price || 0
      product.stock = productData.stock || 0
      product.sales = productData.sales || 0
      // 强制刷新库存信息
      //   refreshProductStock(productData.id).then(latestProduct => {
      //     if (latestProduct) {
      //       product.stock = latestProduct.stock || 0
      //       product.sales = latestProduct.sales || 0
      //     }
      //   handleCountChange(product)
      //   ElMessage.success(`已选择商品: ${productData.name}`)
      // })
    }
  }
  currentProductIndex.value = -1
}

// 刷新商品库存信息
// const refreshProductStock = async (productId: number) => {
//   try {
//     // 调用API获取最新商品信息
//     // 这里需要根据你的实际API调整
//     const response = await ProductApi.getDetail(productId)
//     return response.data
//   } catch (error) {
//     console.error('获取商品库存失败:', error)
//     return null
//   }
// }

// 添加商品到合同（修复去重逻辑）
const addProductToContract = (productData: any): boolean => {
  if (!productData.id) return false

  // 检查商品是否已存在
  const existingIndex = dialogProps.value.row.products.findIndex((p: any) => p.pId === productData.id)
  if (existingIndex !== -1) {
    // 商品已存在，增加数量（不超过库存）
    const existingProduct = dialogProps.value.row.products[existingIndex]
    const newCount = existingProduct.count + 1
    if (newCount <= getMaxCount(existingProduct)) {
      existingProduct.count = newCount
      handleCountChange(existingProduct)
    } else {
      ElMessage.warning(`商品 ${productData.name} 已达到最大可购买数量`)
    }
    return false
  } else {
    // 新增商品
    const newProduct = {
      pName: productData.name,
      pId: productData.id,
      price: productData.price || 0,
      count: 1,
      totalPrice: productData.price || 0,
      stock: productData.stock || 0,
      sales: productData.sales || 0
    }
    dialogProps.value.row.products.push(newProduct)
    calculateTotalAmount()
    return true
  }
}

// 计算单个商品小计
const calculateSubtotal = (row: any) => {
  row.totalPrice = parseFloat(((row.price || 0) * (row.count || 0)).toFixed(2))
}

// 计算合同总金额
const calculateTotalAmount = () => {
  const total = dialogProps.value.row.products.reduce((sum: number, item: any) => {
    return sum + (item.totalPrice || 0)
  }, 0)
  dialogProps.value.row.amount = total.toFixed(2)
}

// 数量变化处理
const handleCountChange = (row: any) => {
  // 确保数量为正整数
  row.count = Math.max(1, parseInt(row.count || 1))
  // 不超过最大限制
  const maxCount = getMaxCount(row)
  if (row.count > maxCount) {
    row.count = maxCount
    ElMessage.warning(`数量不能超过 ${maxCount}`)
  }
  // 重新计算小计和总金额
  calculateSubtotal(row)
  calculateTotalAmount()
}

// 获取商品最大可选择数量（关键修复）
const getMaxCount = (row: any): number => {
  // 最大数量 = 当前库存 + 当前已选数量（用于编辑时）
  return (row.stock || 0) + (row.count || 0)
}

// 删除合同商品
const removeContractProduct = (index: number) => {
  dialogProps.value.row.products.splice(index, 1)
  calculateTotalAmount()
}

// 添加空商品行
const addContractProduct = () => {
  dialogProps.value.row.products.push({
    pName: '',
    pId: 0,
    price: 0,
    count: 1,
    totalPrice: 0,
    stock: 0,
    sales: 0
  })
}
</script>

<style scoped>
.flex {
  display: flex;
  gap: 16px;
}

.mr-18px {
  margin-right: 18px;
}

.product-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.stock-info {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
  white-space: nowrap;
}

.stock-warning {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  white-space: nowrap;
}

.error-border {
  border-color: #f56c6c;
}

.text-gray {
  color: #909399;
}

.amount-summary {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;
}
</style>
